<template>
  <el-form ref="deptForm" :rules="rules" :model="form" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getDepartmentSimple,
  addDepartment,
  getDepartmentDetail,
  editDepartment
} from '@/api/departments'

export default {
  name: 'VueHr8801DeptDialog',
  props: {
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    orangeList: {
      type: Array,
      required: true
    }
  },

  data() {
    // 自定义效验函数
    const existCodeValid = (rules, value, callback) => {
      // 验证输入的编码value在所有的部门中是否存在
      let exisCodeList = this.orangeList.map((item) => item.code)
      // 判断编辑状态
      if (this.isEdit) {
        // 根据id将当前编辑部门id所有的部门中移除
        exisCodeList = this.orangeList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
      }
      if (exisCodeList.includes(value)) {
        // 存在效验失败
        callback(new Error(`部门编码${value}已存在`))
      } else {
        // 不存在 放行 效验成功
        callback()
      }
    }
    // 自定义效验函数
    const existNameValid = (rules, value, callback) => {
      let existNameList = this.orangeList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name)
      if (this.isEdit) {
        const pid = this.orangeList.find((item) => item.id === this.id).pid
        const brothers = this.orangeList.filter((item) => item.pid === pid)
        existNameList = brothers
          .filter((item) => item.id !== this.id)
          .map((item) => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error(`部门名称${value}已存在`))
      } else {
        callback()
      }
    }
    return {
      // 表单收集的对象
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: this.id
      },

      // 保存部门的负责人
      list: [],
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '请输入长度为1-50的部门名称',
            trigger: 'blur'
          },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '请输入长度为1-50的部门编码',
            trigger: 'blur'
          },
          { validator: existCodeValid, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择部门负责人', trigger: 'blur' }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '请输入长度为1-50的部门介绍',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  // 解决数据不更新的方式3
  watch: {
    // 监听watch 侦听id的变化  一旦变化 就重新调用 获取详情数据 重新填充表单
    // id: function(new_value, old_value) {
    //   console.log('新', new_value)
    //   console.log('旧', old_value)
    //   this.loadDepartmentDetail()
    // }
    // 对于复杂的数据类型可以开启深度侦听获取需要页面打开就立即加载
    // id: {
    //   handler: function(new_value, old_value) {
    //     console.log('新', new_value)
    //     console.log('旧', old_value)
    //     this.loadDepartmentDetail()
    //   },
    // deep:true 深度监听
    // 立即加载
    //   immediate: true
    // }
  },

  mounted() {},
  created() {
    this.loadDepartmentSimple()
    if (this.isEdit) {
      this.loadDepartmentDetail()
    }
  },

  methods: {
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 加载部门信息
    async loadDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.id)
        console.log(res)
        this.form = res.data
        this.$message.success(res.message)
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑部门
    async doEdit() {
      try {
        const res = await editDepartment(this.form)
        console.log(res)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 新增子部门
    async doAdd() {
      try {
        const res = await addDepartment(this.form)
        console.log(res)
        this.$message.success(res.message)
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门的负责人
    async loadDepartmentSimple() {
      try {
        const res = await getDepartmentSimple()
        console.log(res, '12312312')
        this.$message.success(res.message)
        this.list = res.data
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      // 完成兜底效验
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.$emit('cancel')
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
